package cn.teduymdj.jxc.repo.impl;


import cn.teduymdj.jxc.pojo.vo.GoodsListItemVO;
import cn.teduymdj.jxc.pojo.vo.GoodsStandardVO;
import cn.teduymdj.jxc.repo.GoodsRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class GoodsRedisRepositoryImpl implements GoodsRedisRepository {
    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;
    public GoodsRedisRepositoryImpl() {
        log.debug("创建处理缓存的数据访问对象:GoodsRedisRepositoryImpl");
    }

    @Override
    public void save(GoodsStandardVO goodsStandardVO) {
        String key = GOOD_ITEM_KEY_PREFIX+goodsStandardVO.getId();
        redisTemplate.opsForSet().add(GOOD_ITEM_KEYS_KEY,key);
        redisTemplate.opsForValue().set(key, goodsStandardVO);
    }

    @Override
    public void save(List<GoodsListItemVO> goods) {
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        for (GoodsListItemVO good : goods) {
            ops.rightPush(GOOD_LIST_KEY,good);
        }
    }

    @Override
    public Long deleteAll() {
        Set<Serializable> members = redisTemplate.opsForSet().members(GOOD_ITEM_KEYS_KEY);
        Set<String> keys = new HashSet<>();
        for (Serializable member : members) {
            keys.add((String) member);
        }
        keys.add(GOOD_LIST_KEY);
        keys.add(GOOD_ITEM_KEYS_KEY);
        return redisTemplate.delete(keys);
    }

    @Override
    public GoodsStandardVO get(Long id) {
        Serializable serializable = redisTemplate.opsForValue().get(GOOD_ITEM_KEY_PREFIX + id);
        GoodsStandardVO standardVO = null;
        if (serializable!=null){
            if (serializable instanceof GoodsStandardVO){
                standardVO = (GoodsStandardVO) serializable;
            }
        }
        return standardVO;
    }

    @Override
    public List<GoodsListItemVO> list() {
        Long start = 0L;
        Long end = -1L;
        return list(start,end);
    }

    @Override
    public List<GoodsListItemVO> list(Long start,Long end) {
        List<Serializable> range = redisTemplate.opsForList().range(GOOD_LIST_KEY, start, end);
        List<GoodsListItemVO> brandListItemVOS = new ArrayList<>();
        if (range!=null){
            for (Serializable serializable : range) {
                brandListItemVOS.add((GoodsListItemVO)serializable);
            }
        }
        return brandListItemVOS;
    }

}
